package com.lun.blog.service.impl;

import com.lun.blog.pojo.Comment;
import com.lun.blog.repostory.CommentRepository;
import com.lun.blog.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author fangLJ
 * @creatTime 2021/3/10
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentRepository commentRepository;

    @Override
    public List<Comment> findByBlogId(Long id) {
        return commentRepository.findByBlog_Id(id);
    }

    @Override
    public Long countComment() {
        return commentRepository.count();
    }

    @Override
    public Comment saveComment(Comment comment) {
        Long parentId = comment.getParentComment().getId();
        if(parentId != -1){
            comment.setParentComment(commentRepository.findById(parentId).get());
        }else {
            comment.setParentComment(null);
        }
        comment.setCreateTime(new Date());
        return commentRepository.save(comment);
    }

    @Override
    public List<Comment> getByBlogId(Long blogId) {
        List<Comment> comment = commentRepository.findComment(blogId);
        return eachComment(comment);
    }

    /**
     *
     * @param root 顶级的评论信息
     * @return 返回处理之后的节点信息
     */
    public List<Comment> eachComment(List<Comment> root){
        List<Comment> returnComment = new ArrayList<>();
        for (Comment comment : root) {
            Comment comment1 = new Comment();
            BeanUtils.copyProperties(comment,comment1);
            List<Comment> childComment = childComment(new ArrayList<>(), comment);
            if(!CollectionUtils.isEmpty(childComment)){
                //移除根节点
                Iterator<Comment> iterator = childComment.iterator();
                while (iterator.hasNext()){
                    Comment comment2 = iterator.next();
                    if(comment.getId().equals(comment2.getId())){
                        iterator.remove();
                    }
                }
                comment1.setReplayComment(childComment);
            }
            returnComment.add(comment1);
        }

        return returnComment;
    }

    /**
     *
     * @param comment 顶级的评论信息
     * @return 返回当前顶级评论的回复信息
     */
    public List<Comment> childComment(List<Comment>list,Comment comment){
        List<Comment> commentList = commentRepository.findByParentComment_Id(comment.getId());
        if(!CollectionUtils.isEmpty(commentList)){
            for (Comment comment1 : commentList) {
                comment1.setParentComment(comment);
                childComment(list,comment1);
            }
        }
        list.add(comment);
        return list;
    }
}
